import fs from 'fs-extra'
import path from 'path'
import axios from 'axios'
import { gt } from 'lodash'
import chalk from 'chalk'
import { input, select } from '@inquirer/prompts'
import { clone } from '../utils/clone'
import { name, version } from '../../package.json'



interface ITemplateInfo {
    name?: string // module name
    downloadUrl: string // download url
    description?: string // module description
    branch: string // module branch
}

export const templates: Map<string, ITemplateInfo> = new Map([
    ['Vite-Vue3-Typescript-template',
        {
            name: 'Vite-Vue3-Typescript-template',
            downloadUrl: 'https://gitee.com/yang-guo1314/vue3-ts-enterprise-framework.git',
            description: 'Vite-Vue3-Typescript-template',
            branch: 'master'
        }]
])

export const isOverwrite = async (projectName: string) => {
    console.warn(`${projectName}文件夹已存在，是否覆盖？`)
    const run = await select({
        message: `${projectName} 文件夹已存在，是否覆盖？`,
        choices: [
            {
                name: '覆盖',
                value: true
            },
            {
                name: '不覆盖',
                value: false
            }
        ]
    })
    return run
}

export const getNameInfo = async () => {
    const npmUrl = `https://registry.npmjs.org/${name}`
    let res
    try {
        res = await axios.get(npmUrl)
    } catch (e) { }
    return res
}

export const getNpmLasterVersion = async (name: string) => {
    const { data } = await getNameInfo() as any
    console.log(data['dist-tags']?.latest, '--------------')
    return data['dist-tags']?.latest
}

export const checkUpdate = async (name: string, version: string) => {
    const lasterVersion = await getNpmLasterVersion(name)
    const need = gt(lasterVersion, version)
    if (need) {
        console.warn(`检测到最新版本：${chalk.blackBright(lasterVersion)}, 当前版本是 ${chalk.blackBright(version)}`)
        console.log(`可使用：${chalk.yellow('npm install hans-cli-plus')}, 或者使用：${chalk.yellow('pnpm install hans-cli-plus')}`)
    }
    return need
}

export const create = async (projectName?: string) => {
    // 初始化模版列表
    const templateList = Array.from(templates).map((item: [string, ITemplateInfo]) => {
        const [name, info] = item
        return {
            name,
            description: info.description,
            value: name
        }
    })
    if (!projectName) {
        projectName = await input({
            message: '请输入项目名称',
        })
    }

    // 如果文件夹存在，则提示是否覆盖
    const filePath = path.resolve(process.cwd(), projectName)
    if (fs.existsSync(filePath)) {
        const run = await isOverwrite(projectName)
        if (run) {
            await fs.remove(filePath)
        } else {
            return
        }
    }

    // 检测版本更新
    await checkUpdate(name, version)


    const templateName = await select({
        message: '请选择模版',
        choices: templateList
    })
    const info = templates.get(templateName)
    if (info) {
        clone(info.downloadUrl, projectName, ['-b', info.branch])
    }
    console.log(projectName, templateName, info)
}